import { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router";
import { toast } from "./utilities";
import NewLink from "./NewLink";
import classes from "./LicensePage.module.css";
import type { License } from "./declarations/Licenses";
import { type Dialog, type TextField } from "./mdui";

const LicensePage = () => {
  const [license, setlicense] = useState<License[]>([]);
  const [compName, setcompName] = useState<string>("");
  const dlgReference = useRef<Dialog>(null);
  const textReference = useRef<TextField>(null);
  const nav = useNavigate();

  useEffect(() => {
    fetch("./oss-licenses.json")
      .then((resp) => {
        if (!resp.ok) {
          throw new Error("数据接收错误");
        }
        return resp.json();
      })
      .then((licenses) => {
        setlicense([...(licenses as License[])]);
      })
      .catch(() => {
        toast("数据接收错误，返回上一页面", () => {
          void nav(-1);
        });
      });
  }, [nav]);

  return (
    <main className={classes.page}>
      <mdui-dialog close-on-overlay-click ref={dlgReference}>
        <mdui-text-field
          variant="outlined"
          autosize
          label="许可声明"
          ref={textReference}
          readonly
        ></mdui-text-field>
        <mdui-button
          slot="action"
          variant="text"
          href={`https://www.npmjs.com/package/${compName}`}
          target="_blank"
          rel="nofollow"
        >
          访问组件 NPM
        </mdui-button>
        <mdui-button
          slot="action"
          variant="text"
          onClick={() => {
            if (dlgReference.current) {
              dlgReference.current.open = false;
            }
          }}
        >
          关闭
        </mdui-button>
      </mdui-dialog>
      <p>
        版本{" "}
        <code>
          {__VERSION__} (
          <NewLink
            url={
              "https://gitee.com/lemon399/code-share-page/commit/" + __HASH__
            }
            text={__SHORT_HASH__}
          />
          )
        </code>
        <br />
        编译时间 <code>{__BUILD_TIME__}</code>
        <br />
        本项目以 <NewLink
          url="http://unlicense.org"
          text="The Unlicense"
        />{" "}
        许可证发布，没有任何条件和担保。源代码托管于{" "}
        <NewLink
          url="https://gitee.com/lemon399/code-share-page"
          text="Gitee"
        />{" "}
        。
      </p>
      <p>
        本项目包含了以下共 {String(license.length)} 个开源组件的代码，
        感谢这些个人、社区和组织的无私奉献！
        点击下列组件卡片查看组件的许可声明。
      </p>
      <section className="flex-around">
        <mdui-button
          variant="tonal"
          onClick={() => {
            void nav(-1);
          }}
        >
          返回
        </mdui-button>
      </section>
      {license.map((lic) => (
        <mdui-card
          key={lic.name}
          clickable
          onClick={() => {
            setcompName(lic.name);
            const dialog = dlgReference.current;
            const text = textReference.current;
            if (dialog && text) {
              text.value = lic.licenseText;
              dialog.open = true;
            }
          }}
        >
          {[lic.name, lic.version, lic.author, lic.license].map(
            (string_, index) => (
              <div key={index}>
                <code>
                  {string_ === undefined ? (
                    "作者未知"
                  ) : typeof string_ == "object" ? (
                    <NewLink url={string_.url} text={string_.name} />
                  ) : (
                    string_
                  )}
                </code>
              </div>
            ),
          )}
        </mdui-card>
      ))}
    </main>
  );
};

export default LicensePage;
